<?php

namespace App\Http\Controllers;

use App\Clientele;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Intervention\Image\Facades\Image;

class ApplyController extends Controller
{

    /**
     * 制作海报
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function makePoster(Request $request)
    {


        // 判断是否是post提交
        if ($request->isMethod('post')) {
            // 表单验证
//            $validate = \Validator::make($request->all(), [
//                'name' => 'required'
//            ], [
//
//                'name.required' => '不能为空',
//            ]);
//
//            if ($validate->fails()) {
//                return redirect('makeposter')->withErrors($validate)->withInput();
//            }

            // 接收表单数据
            $image = $request->input('image');
            $they = $request->input('they');
            $myself = $request->input('myself');
            $role = $request->input('role');
            $name = $request->input('name');


            // 将base64图片处理成image
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {

                $type = $result[2]; // 后缀
                $image = base64_decode(str_replace($result[1], '', $image)); // 图片
                $imageName = 'uploads/' . str_random() . '.' . $type; // 新文件名
                \Storage::put($imageName, $image . $type); // 保存
            }

            // 处理图片
            $poster = \Image::make(\Storage::get($imageName))->encode('jpg', 100);  // 读取图片
//            $poster->fill('images/watermark/mask.png'); // 加遮罩
            $poster->resize(648, 1020); // 固定尺寸
            $poster->insert('images/watermark/watermark.png', 'bottom-right', 0, 0); // 水印

            // 写字（用户）
            $poster->text($they, 585, 700, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(30);
                $font->color('#31f5ff');
                $font->align('right');
            });
            $poster->text($they, 585, 700, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(30);
                $font->color('#31f5ff');
                $font->align('right');
            });
            $poster->text($they, 585, 700, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(30);
                $font->color('#31f5ff');
                $font->align('right');
            });


            $poster->text($myself, 585, 785, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(30);
                $font->color('#31f5ff');
                $font->align('right');
            });
            $poster->text($myself, 585, 785, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(30);
                $font->color('#31f5ff');
                $font->align('right');
            });


            if ($role == '0') {
                $str = '我是吃瓜群众';
            } else if ($role == '1') {
                $str = "我是讲师";
            } else {
                $str = "我是评委";
            }

            $poster->text($str . '  ' . $name, 585, 835, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(18);
                $font->color('#FFFFFF');
                $font->align('right');
            });
            $poster->text($str . '  ' . $name, 585, 835, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(18);
                $font->color('#FFFFFF');
                $font->align('right');
            });
            $poster->text($str . '  ' . $name, 585, 835, function ($font) {
                $font->file('fonts/YaHei.ttf');
                $font->size(18);
                $font->color('#FFFFFF');
                $font->align('right');
            });


            // 创建目录 保存
            is_dir(storage_path('app/posters')) ? '' : mkdir(storage_path('app/posters'), 0777, true);
            // 文件名
            $posterName = 'posters/' . str_random() . '.jpg';
            $poster->save(storage_path('app/' . $posterName));

//            return $poster->response('jpg');
            // 保存到数据库
            $cli = new Clientele();

//             微信信息
            $cli->avatar = $this->getWechatInfo()['avatar'];
            $cli->openid = $this->getWechatInfo()['openid'];
            $cli->wechatname = userTextEncode($this->getWechatInfo()['nickname']);

            $cli->image = $imageName;
            $cli->poster = $posterName;
            $cli->role = $role;
            $cli->myself = $myself;
            $cli->they = $they;
            $cli->name = $name;
            $res = $cli->save();

            $id = $cli->id;

            return json('1', '成功', ['id' => $id]);
        } else {
            return view('makeposter');
        }

    }

    /**
     * 申请参加
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function apply(Request $request)
    {
        // 判断是否是post提交
        if ($request->isMethod('post')) {


            // 更新数据
            $clis = Clientele::where('openid', $this->getWechatInfo()['openid'])->get();
            $cli = $clis->last();

            $cli->username = $request->input('username');
            $cli->age = $request->input('age');
            $cli->sex = $request->input('sex');
            $cli->city = $request->input('city');
            $cli->location = $request->input('location');
            $cli->position = $request->input('position');
            $cli->phone = $request->input('phone');
            $cli->company = $request->input('company');


            $cli->save();

            // 跳转到支付
            return redirect('https://trade.koudaitong.com/wxpay/confirmQr?qr_id=4537044&kdt_id=16886109');


        } else {
            return view('apply');
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function poster($id)
    {
        $cli = Clientele::findOrFail($id);

        $poster = \Storage::url('app/' . $cli->poster);


        return view('poster', compact('poster'));

    }

    /**
     * 获取微信信息
     *
     * @return array
     */
    protected function getWechatInfo()
    {
        // 微信用户信息
        $userInfo = session('wechat.oauth_user')->toArray();

        return [
            'openid' => $userInfo['id'],
            'nickname' => $userInfo['nickname'],
            'avatar' => $userInfo['avatar'],

        ];
    }


}
